<template>
  <ElCard class="hfull p20px">
    <template #header>
      <div class="card-header">
        <span>用户登录</span>
      </div>
    </template>
    <el-form label-position="right" label-width="100px" :model="data" class="p10">
      <el-form-item label="用户名">
        <el-input v-model="data.username" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input type="password" v-model="data.password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex-center">
        <ElButton type="primary" @click="login">登录</ElButton>
        <ElButton @click="regist">注册</ElButton>
      </div>
    </template>
  </ElCard>
</template>
<script setup lang="ts">
  import { ElButton, ElInput, ElForm, ElFormItem, ElCard } from 'element-plus'
  import { reactive, watch, ref, onMounted } from 'vue'
  import { loginApi } from '@/api'
  import fb from '@/utils/feedback'
  import { useRouter } from 'vue-router'
  import type { RouteLocationNormalizedLoaded } from 'vue-router'
  import { useUserStore } from '@/store'
  import { useWatermark } from '@/hooks/web/useWatermark'

  const { setWatermark } = useWatermark()
  const { currentRoute, replace, push } = useRouter()
  const userStore = useUserStore()
  const data = reactive({
    username: '',
    password: ''
  })

  const login = async () => {
    const res = await loginApi(data)
    await userStore.login(res)
    replace('/')
    if(redirect.value) push({ path: redirect.value})
  }

  const regist = () => replace('/regist')

  onMounted(() => setWatermark('请登录'))

  const redirect = ref<string>('')
  watch(
    () => currentRoute.value,
    (route: RouteLocationNormalizedLoaded) => redirect.value = route?.query?.redirect as string,
    { immediate: true }
  )
</script>